/**
 * 
 */
package org.framework2.utils;

import java.io.StringReader;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * XML文件接续工具
 * @author ahli
 */
public class XMLReader {

	private String xmlData = null;
	
	private Document doc = null;
	
	private SAXReader reader = new SAXReader();
	
	private Element root = null;
	
	public XMLReader(String xmlData) throws DocumentException{
		this.xmlData = xmlData;
		
		// 解析XML
		doc = reader.read(new StringReader(xmlData));
		
		root = doc.getRootElement();
	}
	
	/**
     * 获取xml的节点值
     * 
     * 如果xml文件格式如下：
     * 
     * <root> <stu1> <name1 shortname="dog">zhangsan<name1> <address1>ddd</address1>
     * </stu1> <stu2> <name2 shortname="pig">lisi<name2> <address2>abc</address2>
     * </stu2> </root> 调用规则：
     * 
     * 要想获取节点name1的值可以通过 getContent("root.stu1.name1")
     * getContent("root\\stu1\\name1") getContent("root/stu1/name1")三种来获取
     * 
     * 目前只支持通过.的方式来获取
     * 
     * @param nodeName
     * @return
     */
    public String getNodeText(String nodeName)
    {
        Element tmpElement = getElementByString(nodeName);

        if (tmpElement == null)
        {
            return null;
        }

        return tmpElement.getText();
    }
    
    /**
     * 根据字符串获取最底层的Element对象
     * 
     * @param elementName
     * @return
     */
    private Element getElementByString(String nodeName)
    {
        if (nodeName == null || "".equals(nodeName.trim()))
        {
            return null;
        }

        String tempNodeName = nodeName;
        String str[] = getStringBySeparator(tempNodeName);

        if (str == null)
        {
            if (root.getName().equals(nodeName))
            {
                // Log.system.debug("log.global.endMethod");
                return root;
            }

            return null;
        }

        Element node = root;
        for (int i = 1; i < str.length; i++)
        {
            node = getChildNodeByName(node, str[i]);

            if (node == null)
            {
                return null;
            }
        }

        return node;
    }
    
	public String getSrcXMLData(){
		return xmlData;
	}
	
	/**
     * 根据分隔符来获取字符数组
     * 
     * @param str
     * @return
     */
    private static String[] getStringBySeparator(String str)
    {
        if (str == null)
        {
            return null;
        }

        if (str.indexOf(".") != -1)
        {
            return str.split("\\.");
        }

        if (str.indexOf("\\") != -1)
        {
            return str.split("\\\\");
        }

        if (str.indexOf("/") != -1)
        {
            return str.split("/");
        }

        return null;

    }
    
    /**
     * 通过父节点和子节点名称查询子节点
     * 
     * @param start
     * @param childNodeName
     * @return
     */
	@SuppressWarnings("unchecked")
	private static Element getChildNodeByName(Element start,
            String childNodeName)
    {
        if (start == null || childNodeName == null || "".equals(childNodeName))
        {
            return null;
        }

        Element child = null;
        Element _child = null;
        if (start.getNodeType() == Element.ELEMENT_NODE)
        {
            for (@SuppressWarnings("rawtypes")
			Iterator i = start.elementIterator(); i.hasNext();)
            {
                child = (Element) i.next();

                if (childNodeName.equals(child.getName()))
                {
                	_child = child;
                }
            }
        }
        return _child;
    }
	
//	public static void main(String[] args) throws DocumentException {
//		
//		StringBuilder sb = new StringBuilder(5000);
//		sb.append("");
//		/*
//		<?xml version="1.0" encoding="UTF-8"?>
//		<InnerBus>
//			<ProcID>4201009161453317460000143</ProcID>
//			<SvcCont>
//				<RbtDeployNotifyReq>
//					<ProvinceID>13</ProvinceID>
//					<AccessPlatformID>0011001</AccessPlatformID>
//					<EventType>2</EventType>
//					<ToneID>600902000006262125</ToneID>
//				</RbtDeployNotifyReq>
//			</SvcCont>
//		</InnerBus>		*/
//		
//		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
//		sb.append("<InnerBus>");
//		sb.append("<ProcID>4201009161453317460000143</ProcID>");
//		sb.append("<SvcCont>");
//		sb.append("<RbtDeployNotifyReq>");
//		sb.append("<ProvinceID>13</ProvinceID>");
//		sb.append("<AccessPlatformID>0011001</AccessPlatformID>");
//		sb.append("<EventType>2</EventType>");
//		sb.append("<ToneID>600902000006262125</ToneID>");
//		sb.append("</RbtDeployNotifyReq>");
//		sb.append("</SvcCont>");
//		sb.append("</InnerBus>");
//		
//		System.out.println(new XMLReader(sb.toString()).getNodeText("InnerBus.SvcCont.RbtDeployNotifyReq.TransactionID"));
//		System.out.println(new XMLReader(sb.toString()).getNodeText("InnerBus.SvcCont.RbtDeployNotifyReq.ToneID"));
//	}
}
